Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
How to check contents of input in "real time"

I'm working on a web form and it's been set up with a text field to receive what is expected to be a numeric value. The form won't submit if the contents of this field aren't numeric but there was no error message put in place to let the user know that they filled this field out wrong.

My question is...is there a way in real time to check what's in the input and do something to tell the user they aren't filling it out properly? If everything is ok I want the border of the input to be green, if not then make the border red and change the default text of the input to tell them we only want numbers.

This is loosely what I've got so far as my starting point...

HTML:

<input type="text" class="btn-blue" id="testing"></input>

JS:

$('#testing').attr('placeholder', 'Enter Amount');
var useramount = $("#testing").val();
if (useramount.match(/^\d+$/)) {
   $("#testing").css({border: "2px solid #33CC00 !important"});
} 
else {
  $("#testing").css({border: "2px solid #FF0000 !important"});
  $("#testing").innerHTML = "";
  $('#testing').attr('placeholder', 'Only Numbers Please');
}

I've borrowed the basic principle of the validation from this previously asked question: Check If only numeric values were entered in input. (jQuery)

Any help is greatly appreciated.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can use the input event to get changes when the user is typing inside of the field. On the change event you will be given the element corresponding to the input element the event listener is attached to as event.target. Using this reference you are able to get the value of the input by using the value property on the element.

After you have retrieved the value you will need to verify that it is in fact numerical. Thankfully jQuery provides a method called isNumeric that allows us to do just that.

Once we've established the fact that the value is indeed numerical you can either apply a class or just set the style to what you want to be. Make sure you also check if the value has been emptied so the user does not get confused.

As for the validation message - it's not a good idea to set the value of the input as the user is interacting with said element. Instead I've chosen to add textual element to represent the message that will be shown conditionally based on the validation state.

// Add error message element after input.
$('#some-number').after('<span class="error-message">Please enter numbers only!</span>')

$('#some-number').on('input', function (evt) {
  var value = evt.target.value
  
  if (value.length === 0) {
    evt.target.className = ''
    return
  }

  if ($.isNumeric(value)) {
    evt.target.className = 'valid'
  } else {
    evt.target.className = 'invalid'
  }
})
input {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: none;
  border: 1px solid black;
}

input.valid {
  border: 1px solid green;
}

input.invalid {
  border: 1px solid red;
}

input.invalid + .error-message {
  display: initial;
}

.error-message {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="some-number">

over 4 years ago · Santiago Trujillo Relatório

0

You could bind your validation logic to a keypress event like

$('#target').keydown(function () {
    // validation
});

or

$("#target").blur(function() {
    // validation
});

Example:

https://jsfiddle.net/smzob72e/

over 4 years ago · Santiago Trujillo Relatório

0

You can do this with the onkeypress Event. Every time the user presses a key while the input box is selected, update the input's value.

Example:

var input = document.getElementById("input-box");
var inputValue = document.getElementById("input-box").value;

input.addEventListener("keypress", function() {
  inputValue = document.getElementById("input-box").value;
  // do something with it
});
<input id="input-box"/>

I hope I didn't get anything wrong.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda